In [2]:
import networkx as nx
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import warnings
from custom import custom_funcs as cf

warnings.filterwarnings('ignore')

%load_ext autoreload
%autoreload 2
%matplotlib inline

Nodes and Edges: How do we represent relationships between individuals using NetworkX?

As mentioned earlier, networks, also known as graphs, are comprised of individual entities and their representatives. The technical term for these are nodes and edges, and when we draw them we typically use circles (nodes) and lines (edges).

In this notebook, we will work with a social network of seventh graders, in which nodes are individual students, and edges represent their relationships. Edges between individuals show how often the seventh graders indicated other seventh graders as their favourite.

Data credit: http://konect.uni-koblenz.de/networks/moreno_seventh

Data Representation

In the networkx implementation, graph objects store their data in dictionaries.

Nodes are part of the attribute Graph.node, which is a dictionary where the key is the node ID and the values are a dictionary of attributes.

Edges are part of the attribute Graph.edge, which is a nested dictionary. Data are accessed as such: G.edge[node1][node2]['attr_name'].

Because of the dictionary implementation of the graph, any hashable object can be a node. This means strings and tuples, but not lists and sets.

Load Data

Let's load some real network data to get a feel for the NetworkX API. This dataset comes from a study of 7th grade students.

This directed network contains proximity ratings between studetns from 29 seventh grade students from a school in Victoria. Among other questions the students were asked to nominate their preferred classmates for three different activities. A node represents a student. An edge between two nodes shows that the left student picked the right student as his answer. The edge weights are between 1 and 3 and show how often the left student chose the right student as his favourite.


In [3]:
G = cf.load_seventh_grader_network()

Basic Network Statistics

Let's first understand how many students and friendships are represented in the network.


In [4]:
# Who are represented in the network?
G.nodes()


Out[4]:
[1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 26,
 27,
 28,
 29]

Exercise

Can you write a single line of code that returns the number of nodes in the graph?


In [5]:
len(G.nodes())
# len(G)


Out[5]:
29

Let's now figure out who is connected to who in the network


In [6]:
# Who is connected to who in the network?
G.edges()


Out[6]:
[(1, 2),
 (1, 3),
 (1, 4),
 (1, 5),
 (1, 6),
 (1, 7),
 (1, 8),
 (1, 9),
 (1, 10),
 (1, 11),
 (1, 12),
 (1, 13),
 (1, 14),
 (1, 15),
 (2, 1),
 (2, 3),
 (2, 4),
 (2, 5),
 (2, 6),
 (2, 8),
 (2, 9),
 (2, 11),
 (2, 12),
 (2, 16),
 (2, 17),
 (2, 18),
 (2, 19),
 (2, 20),
 (2, 21),
 (3, 1),
 (3, 2),
 (3, 4),
 (3, 5),
 (3, 6),
 (3, 8),
 (3, 9),
 (3, 11),
 (3, 12),
 (3, 13),
 (3, 15),
 (3, 19),
 (3, 20),
 (3, 21),
 (3, 23),
 (3, 24),
 (3, 25),
 (4, 1),
 (4, 2),
 (4, 3),
 (4, 5),
 (4, 6),
 (4, 7),
 (4, 8),
 (4, 9),
 (4, 10),
 (4, 11),
 (4, 12),
 (4, 13),
 (4, 14),
 (4, 15),
 (4, 16),
 (4, 17),
 (4, 18),
 (4, 19),
 (4, 20),
 (4, 21),
 (4, 23),
 (4, 25),
 (4, 26),
 (5, 1),
 (5, 2),
 (5, 3),
 (5, 4),
 (5, 6),
 (5, 7),
 (5, 8),
 (5, 9),
 (5, 10),
 (5, 11),
 (5, 12),
 (5, 13),
 (5, 14),
 (5, 15),
 (5, 16),
 (5, 17),
 (5, 18),
 (5, 19),
 (5, 20),
 (5, 21),
 (5, 23),
 (5, 24),
 (5, 25),
 (5, 26),
 (5, 27),
 (5, 28),
 (5, 29),
 (6, 1),
 (6, 2),
 (6, 3),
 (6, 4),
 (6, 5),
 (6, 7),
 (6, 8),
 (6, 9),
 (6, 10),
 (6, 11),
 (6, 12),
 (6, 13),
 (6, 14),
 (6, 15),
 (6, 16),
 (6, 17),
 (6, 18),
 (6, 19),
 (6, 20),
 (6, 21),
 (6, 23),
 (6, 24),
 (6, 25),
 (6, 26),
 (6, 27),
 (6, 28),
 (6, 29),
 (7, 1),
 (7, 2),
 (7, 3),
 (7, 4),
 (7, 5),
 (7, 6),
 (7, 8),
 (7, 9),
 (7, 10),
 (7, 13),
 (7, 16),
 (7, 20),
 (8, 2),
 (8, 3),
 (8, 6),
 (8, 9),
 (8, 10),
 (8, 11),
 (8, 12),
 (8, 13),
 (8, 14),
 (8, 15),
 (8, 20),
 (8, 21),
 (8, 23),
 (8, 26),
 (9, 1),
 (9, 2),
 (9, 3),
 (9, 6),
 (9, 7),
 (9, 8),
 (9, 10),
 (9, 11),
 (9, 12),
 (9, 13),
 (9, 14),
 (9, 19),
 (9, 20),
 (9, 21),
 (9, 23),
 (9, 26),
 (10, 1),
 (10, 6),
 (10, 7),
 (10, 8),
 (10, 9),
 (10, 11),
 (10, 14),
 (10, 20),
 (10, 24),
 (10, 25),
 (10, 26),
 (10, 27),
 (11, 8),
 (11, 9),
 (11, 10),
 (11, 12),
 (11, 13),
 (11, 14),
 (11, 15),
 (11, 20),
 (11, 21),
 (11, 23),
 (11, 24),
 (11, 25),
 (11, 26),
 (11, 28),
 (12, 1),
 (12, 2),
 (12, 3),
 (12, 21),
 (12, 6),
 (12, 23),
 (12, 8),
 (12, 9),
 (12, 11),
 (12, 13),
 (13, 2),
 (13, 3),
 (13, 6),
 (13, 8),
 (13, 9),
 (13, 11),
 (13, 12),
 (13, 14),
 (13, 15),
 (13, 20),
 (13, 21),
 (13, 23),
 (13, 25),
 (14, 20),
 (14, 21),
 (14, 23),
 (14, 8),
 (14, 9),
 (14, 11),
 (14, 13),
 (14, 15),
 (15, 24),
 (15, 21),
 (15, 8),
 (15, 25),
 (15, 10),
 (15, 11),
 (15, 12),
 (15, 13),
 (15, 14),
 (16, 17),
 (16, 18),
 (16, 6),
 (16, 5),
 (16, 22),
 (17, 16),
 (17, 19),
 (17, 2),
 (17, 3),
 (17, 4),
 (17, 18),
 (18, 16),
 (19, 2),
 (19, 3),
 (19, 5),
 (19, 6),
 (19, 7),
 (19, 22),
 (20, 3),
 (20, 8),
 (20, 9),
 (20, 11),
 (20, 12),
 (20, 13),
 (20, 14),
 (20, 15),
 (20, 21),
 (20, 23),
 (20, 24),
 (20, 25),
 (20, 26),
 (21, 2),
 (21, 3),
 (21, 6),
 (21, 8),
 (21, 9),
 (21, 11),
 (21, 12),
 (21, 13),
 (21, 14),
 (21, 15),
 (21, 20),
 (21, 23),
 (21, 26),
 (21, 27),
 (21, 29),
 (22, 1),
 (22, 2),
 (22, 5),
 (22, 6),
 (22, 7),
 (22, 8),
 (22, 9),
 (22, 10),
 (22, 11),
 (22, 14),
 (22, 16),
 (22, 17),
 (22, 18),
 (22, 23),
 (22, 24),
 (22, 25),
 (22, 26),
 (22, 28),
 (22, 29),
 (23, 8),
 (23, 9),
 (23, 11),
 (23, 12),
 (23, 13),
 (23, 14),
 (23, 15),
 (23, 20),
 (23, 21),
 (23, 25),
 (23, 26),
 (23, 29),
 (24, 2),
 (24, 3),
 (24, 5),
 (24, 7),
 (24, 10),
 (24, 12),
 (24, 14),
 (24, 15),
 (24, 17),
 (24, 20),
 (24, 21),
 (24, 22),
 (24, 23),
 (24, 25),
 (24, 26),
 (24, 27),
 (25, 17),
 (25, 2),
 (25, 5),
 (25, 22),
 (25, 23),
 (25, 24),
 (25, 10),
 (25, 27),
 (25, 26),
 (25, 14),
 (25, 15),
 (26, 8),
 (26, 9),
 (26, 10),
 (26, 11),
 (26, 12),
 (26, 13),
 (26, 14),
 (26, 15),
 (26, 20),
 (26, 21),
 (26, 23),
 (26, 24),
 (26, 25),
 (26, 27),
 (26, 28),
 (26, 29),
 (27, 8),
 (27, 9),
 (27, 10),
 (27, 11),
 (27, 12),
 (27, 13),
 (27, 14),
 (27, 15),
 (27, 20),
 (27, 21),
 (27, 23),
 (27, 25),
 (27, 26),
 (27, 28),
 (27, 29),
 (28, 9),
 (28, 27),
 (28, 5),
 (28, 22),
 (28, 29),
 (29, 6),
 (29, 27),
 (29, 28),
 (29, 5),
 (29, 22)]

Exercise

Can you write a single line of code that returns the number of relationships represented?


In [6]:
len(G.edges())


Out[6]:
376

Concept

A network, more technically known as a graph, is comprised of:

  • a set of nodes
  • joined by a set of edges

They can be represented as two lists:

  1. A node list: a list of 2-tuples where the first element of each tuple is the representation of the node, and the second element is a dictionary of metadata associated with the node.
  2. An edge list: a list of 3-tuples where the first two elements are the nodes that are connected together, and the third element is a dictionary of metadata associated with the edge.

Since this is a social network of people, there'll be attributes for each individual, such as a student's gender. We can grab that data off from the attributes that are stored with each node.


In [7]:
# Let's get a list of nodes with their attributes.
G.nodes(data=True)

# NetworkX will return a list of tuples in the form (node_id, attribute_dictionary)


Out[7]:
[(1, {'gender': 'male'}),
 (2, {'gender': 'male'}),
 (3, {'gender': 'male'}),
 (4, {'gender': 'male'}),
 (5, {'gender': 'male'}),
 (6, {'gender': 'male'}),
 (7, {'gender': 'male'}),
 (8, {'gender': 'female'}),
 (9, {'gender': 'female'}),
 (10, {'gender': 'female'}),
 (11, {'gender': 'female'}),
 (12, {'gender': 'female'}),
 (13, {'gender': 'female'}),
 (14, {'gender': 'female'}),
 (15, {'gender': 'female'}),
 (16, {'gender': 'male'}),
 (17, {'gender': 'male'}),
 (18, {'gender': 'male'}),
 (19, {'gender': 'male'}),
 (20, {'gender': 'female'}),
 (21, {'gender': 'female'}),
 (22, {'gender': 'male'}),
 (23, {'gender': 'female'}),
 (24, {'gender': 'female'}),
 (25, {'gender': 'female'}),
 (26, {'gender': 'female'}),
 (27, {'gender': 'female'}),
 (28, {'gender': 'female'}),
 (29, {'gender': 'female'})]

Exercise

Can you count how many males and females are represented in the graph?

Hint: You may want to use the Counter object from the collections module.


In [8]:
from collections import Counter
mf_counts = Counter([d['gender'] for n, d in G.nodes(data=True)])

def test_answer(mf_counts):
    assert mf_counts['female'] == 17
    assert mf_counts['male'] == 12
    
test_answer(mf_counts)

Edges can also store attributes in their attribute dictionary.


In [9]:
G.edges(data=True)


Out[9]:
[(1, 2, {'count': 1}),
 (1, 3, {'count': 1}),
 (1, 4, {'count': 2}),
 (1, 5, {'count': 2}),
 (1, 6, {'count': 3}),
 (1, 7, {'count': 3}),
 (1, 8, {'count': 2}),
 (1, 9, {'count': 2}),
 (1, 10, {'count': 1}),
 (1, 11, {'count': 1}),
 (1, 12, {'count': 1}),
 (1, 13, {'count': 1}),
 (1, 14, {'count': 1}),
 (1, 15, {'count': 1}),
 (2, 1, {'count': 1}),
 (2, 3, {'count': 3}),
 (2, 4, {'count': 3}),
 (2, 5, {'count': 3}),
 (2, 6, {'count': 2}),
 (2, 8, {'count': 1}),
 (2, 9, {'count': 3}),
 (2, 11, {'count': 1}),
 (2, 12, {'count': 3}),
 (2, 16, {'count': 1}),
 (2, 17, {'count': 1}),
 (2, 18, {'count': 1}),
 (2, 19, {'count': 3}),
 (2, 20, {'count': 3}),
 (2, 21, {'count': 1}),
 (3, 1, {'count': 1}),
 (3, 2, {'count': 3}),
 (3, 4, {'count': 3}),
 (3, 5, {'count': 3}),
 (3, 6, {'count': 3}),
 (3, 8, {'count': 1}),
 (3, 9, {'count': 3}),
 (3, 11, {'count': 3}),
 (3, 12, {'count': 3}),
 (3, 13, {'count': 1}),
 (3, 15, {'count': 1}),
 (3, 19, {'count': 2}),
 (3, 20, {'count': 3}),
 (3, 21, {'count': 1}),
 (3, 23, {'count': 1}),
 (3, 24, {'count': 2}),
 (3, 25, {'count': 1}),
 (4, 1, {'count': 3}),
 (4, 2, {'count': 3}),
 (4, 3, {'count': 3}),
 (4, 5, {'count': 3}),
 (4, 6, {'count': 3}),
 (4, 7, {'count': 2}),
 (4, 8, {'count': 1}),
 (4, 9, {'count': 1}),
 (4, 10, {'count': 1}),
 (4, 11, {'count': 1}),
 (4, 12, {'count': 2}),
 (4, 13, {'count': 2}),
 (4, 14, {'count': 2}),
 (4, 15, {'count': 2}),
 (4, 16, {'count': 3}),
 (4, 17, {'count': 3}),
 (4, 18, {'count': 1}),
 (4, 19, {'count': 2}),
 (4, 20, {'count': 1}),
 (4, 21, {'count': 2}),
 (4, 23, {'count': 2}),
 (4, 25, {'count': 2}),
 (4, 26, {'count': 2}),
 (5, 1, {'count': 3}),
 (5, 2, {'count': 3}),
 (5, 3, {'count': 3}),
 (5, 4, {'count': 3}),
 (5, 6, {'count': 3}),
 (5, 7, {'count': 3}),
 (5, 8, {'count': 3}),
 (5, 9, {'count': 3}),
 (5, 10, {'count': 3}),
 (5, 11, {'count': 2}),
 (5, 12, {'count': 3}),
 (5, 13, {'count': 3}),
 (5, 14, {'count': 1}),
 (5, 15, {'count': 2}),
 (5, 16, {'count': 3}),
 (5, 17, {'count': 3}),
 (5, 18, {'count': 3}),
 (5, 19, {'count': 3}),
 (5, 20, {'count': 2}),
 (5, 21, {'count': 3}),
 (5, 23, {'count': 2}),
 (5, 24, {'count': 2}),
 (5, 25, {'count': 2}),
 (5, 26, {'count': 3}),
 (5, 27, {'count': 2}),
 (5, 28, {'count': 1}),
 (5, 29, {'count': 1}),
 (6, 1, {'count': 3}),
 (6, 2, {'count': 3}),
 (6, 3, {'count': 3}),
 (6, 4, {'count': 3}),
 (6, 5, {'count': 3}),
 (6, 7, {'count': 3}),
 (6, 8, {'count': 3}),
 (6, 9, {'count': 3}),
 (6, 10, {'count': 1}),
 (6, 11, {'count': 2}),
 (6, 12, {'count': 3}),
 (6, 13, {'count': 3}),
 (6, 14, {'count': 1}),
 (6, 15, {'count': 1}),
 (6, 16, {'count': 3}),
 (6, 17, {'count': 3}),
 (6, 18, {'count': 3}),
 (6, 19, {'count': 3}),
 (6, 20, {'count': 1}),
 (6, 21, {'count': 3}),
 (6, 23, {'count': 2}),
 (6, 24, {'count': 1}),
 (6, 25, {'count': 1}),
 (6, 26, {'count': 1}),
 (6, 27, {'count': 2}),
 (6, 28, {'count': 1}),
 (6, 29, {'count': 1}),
 (7, 1, {'count': 3}),
 (7, 2, {'count': 1}),
 (7, 3, {'count': 2}),
 (7, 4, {'count': 2}),
 (7, 5, {'count': 2}),
 (7, 6, {'count': 3}),
 (7, 8, {'count': 2}),
 (7, 9, {'count': 2}),
 (7, 10, {'count': 1}),
 (7, 13, {'count': 1}),
 (7, 16, {'count': 1}),
 (7, 20, {'count': 1}),
 (8, 2, {'count': 1}),
 (8, 3, {'count': 1}),
 (8, 6, {'count': 1}),
 (8, 9, {'count': 2}),
 (8, 10, {'count': 2}),
 (8, 11, {'count': 3}),
 (8, 12, {'count': 3}),
 (8, 13, {'count': 3}),
 (8, 14, {'count': 3}),
 (8, 15, {'count': 3}),
 (8, 20, {'count': 2}),
 (8, 21, {'count': 3}),
 (8, 23, {'count': 3}),
 (8, 26, {'count': 2}),
 (9, 1, {'count': 1}),
 (9, 2, {'count': 1}),
 (9, 3, {'count': 1}),
 (9, 6, {'count': 1}),
 (9, 7, {'count': 1}),
 (9, 8, {'count': 3}),
 (9, 10, {'count': 2}),
 (9, 11, {'count': 1}),
 (9, 12, {'count': 3}),
 (9, 13, {'count': 3}),
 (9, 14, {'count': 1}),
 (9, 19, {'count': 1}),
 (9, 20, {'count': 3}),
 (9, 21, {'count': 3}),
 (9, 23, {'count': 2}),
 (9, 26, {'count': 1}),
 (10, 1, {'count': 1}),
 (10, 6, {'count': 1}),
 (10, 7, {'count': 1}),
 (10, 8, {'count': 1}),
 (10, 9, {'count': 1}),
 (10, 11, {'count': 1}),
 (10, 14, {'count': 1}),
 (10, 20, {'count': 1}),
 (10, 24, {'count': 1}),
 (10, 25, {'count': 2}),
 (10, 26, {'count': 3}),
 (10, 27, {'count': 1}),
 (11, 8, {'count': 3}),
 (11, 9, {'count': 2}),
 (11, 10, {'count': 1}),
 (11, 12, {'count': 3}),
 (11, 13, {'count': 3}),
 (11, 14, {'count': 1}),
 (11, 15, {'count': 2}),
 (11, 20, {'count': 2}),
 (11, 21, {'count': 3}),
 (11, 23, {'count': 3}),
 (11, 24, {'count': 1}),
 (11, 25, {'count': 1}),
 (11, 26, {'count': 3}),
 (11, 28, {'count': 1}),
 (12, 1, {'count': 1}),
 (12, 2, {'count': 1}),
 (12, 3, {'count': 1}),
 (12, 21, {'count': 3}),
 (12, 6, {'count': 1}),
 (12, 23, {'count': 3}),
 (12, 8, {'count': 3}),
 (12, 9, {'count': 3}),
 (12, 11, {'count': 3}),
 (12, 13, {'count': 3}),
 (13, 2, {'count': 1}),
 (13, 3, {'count': 1}),
 (13, 6, {'count': 1}),
 (13, 8, {'count': 3}),
 (13, 9, {'count': 2}),
 (13, 11, {'count': 3}),
 (13, 12, {'count': 3}),
 (13, 14, {'count': 3}),
 (13, 15, {'count': 3}),
 (13, 20, {'count': 3}),
 (13, 21, {'count': 3}),
 (13, 23, {'count': 3}),
 (13, 25, {'count': 1}),
 (14, 20, {'count': 1}),
 (14, 21, {'count': 3}),
 (14, 23, {'count': 1}),
 (14, 8, {'count': 1}),
 (14, 9, {'count': 1}),
 (14, 11, {'count': 1}),
 (14, 13, {'count': 3}),
 (14, 15, {'count': 3}),
 (15, 24, {'count': 1}),
 (15, 21, {'count': 1}),
 (15, 8, {'count': 1}),
 (15, 25, {'count': 1}),
 (15, 10, {'count': 2}),
 (15, 11, {'count': 1}),
 (15, 12, {'count': 1}),
 (15, 13, {'count': 1}),
 (15, 14, {'count': 3}),
 (16, 17, {'count': 3}),
 (16, 18, {'count': 3}),
 (16, 6, {'count': 3}),
 (16, 5, {'count': 2}),
 (16, 22, {'count': 1}),
 (17, 16, {'count': 3}),
 (17, 19, {'count': 2}),
 (17, 2, {'count': 1}),
 (17, 3, {'count': 1}),
 (17, 4, {'count': 1}),
 (17, 18, {'count': 1}),
 (18, 16, {'count': 3}),
 (19, 2, {'count': 3}),
 (19, 3, {'count': 3}),
 (19, 5, {'count': 1}),
 (19, 6, {'count': 1}),
 (19, 7, {'count': 1}),
 (19, 22, {'count': 1}),
 (20, 3, {'count': 1}),
 (20, 8, {'count': 2}),
 (20, 9, {'count': 3}),
 (20, 11, {'count': 2}),
 (20, 12, {'count': 3}),
 (20, 13, {'count': 2}),
 (20, 14, {'count': 1}),
 (20, 15, {'count': 1}),
 (20, 21, {'count': 2}),
 (20, 23, {'count': 2}),
 (20, 24, {'count': 1}),
 (20, 25, {'count': 1}),
 (20, 26, {'count': 2}),
 (21, 2, {'count': 1}),
 (21, 3, {'count': 1}),
 (21, 6, {'count': 1}),
 (21, 8, {'count': 3}),
 (21, 9, {'count': 3}),
 (21, 11, {'count': 3}),
 (21, 12, {'count': 3}),
 (21, 13, {'count': 3}),
 (21, 14, {'count': 1}),
 (21, 15, {'count': 3}),
 (21, 20, {'count': 3}),
 (21, 23, {'count': 3}),
 (21, 26, {'count': 1}),
 (21, 27, {'count': 1}),
 (21, 29, {'count': 1}),
 (22, 1, {'count': 2}),
 (22, 2, {'count': 2}),
 (22, 5, {'count': 3}),
 (22, 6, {'count': 3}),
 (22, 7, {'count': 1}),
 (22, 8, {'count': 1}),
 (22, 9, {'count': 2}),
 (22, 10, {'count': 1}),
 (22, 11, {'count': 1}),
 (22, 14, {'count': 3}),
 (22, 16, {'count': 2}),
 (22, 17, {'count': 1}),
 (22, 18, {'count': 1}),
 (22, 23, {'count': 2}),
 (22, 24, {'count': 1}),
 (22, 25, {'count': 1}),
 (22, 26, {'count': 1}),
 (22, 28, {'count': 1}),
 (22, 29, {'count': 1}),
 (23, 8, {'count': 3}),
 (23, 9, {'count': 3}),
 (23, 11, {'count': 3}),
 (23, 12, {'count': 3}),
 (23, 13, {'count': 3}),
 (23, 14, {'count': 1}),
 (23, 15, {'count': 1}),
 (23, 20, {'count': 3}),
 (23, 21, {'count': 3}),
 (23, 25, {'count': 1}),
 (23, 26, {'count': 1}),
 (23, 29, {'count': 1}),
 (24, 2, {'count': 1}),
 (24, 3, {'count': 1}),
 (24, 5, {'count': 1}),
 (24, 7, {'count': 1}),
 (24, 10, {'count': 1}),
 (24, 12, {'count': 1}),
 (24, 14, {'count': 2}),
 (24, 15, {'count': 2}),
 (24, 17, {'count': 1}),
 (24, 20, {'count': 3}),
 (24, 21, {'count': 1}),
 (24, 22, {'count': 2}),
 (24, 23, {'count': 3}),
 (24, 25, {'count': 3}),
 (24, 26, {'count': 3}),
 (24, 27, {'count': 3}),
 (25, 17, {'count': 1}),
 (25, 2, {'count': 1}),
 (25, 5, {'count': 1}),
 (25, 22, {'count': 1}),
 (25, 23, {'count': 3}),
 (25, 24, {'count': 3}),
 (25, 10, {'count': 1}),
 (25, 27, {'count': 3}),
 (25, 26, {'count': 3}),
 (25, 14, {'count': 1}),
 (25, 15, {'count': 3}),
 (26, 8, {'count': 2}),
 (26, 9, {'count': 2}),
 (26, 10, {'count': 3}),
 (26, 11, {'count': 3}),
 (26, 12, {'count': 1}),
 (26, 13, {'count': 1}),
 (26, 14, {'count': 3}),
 (26, 15, {'count': 3}),
 (26, 20, {'count': 3}),
 (26, 21, {'count': 1}),
 (26, 23, {'count': 2}),
 (26, 24, {'count': 2}),
 (26, 25, {'count': 3}),
 (26, 27, {'count': 1}),
 (26, 28, {'count': 1}),
 (26, 29, {'count': 1}),
 (27, 8, {'count': 3}),
 (27, 9, {'count': 2}),
 (27, 10, {'count': 1}),
 (27, 11, {'count': 1}),
 (27, 12, {'count': 3}),
 (27, 13, {'count': 3}),
 (27, 14, {'count': 1}),
 (27, 15, {'count': 1}),
 (27, 20, {'count': 2}),
 (27, 21, {'count': 3}),
 (27, 23, {'count': 3}),
 (27, 25, {'count': 2}),
 (27, 26, {'count': 2}),
 (27, 28, {'count': 3}),
 (27, 29, {'count': 3}),
 (28, 9, {'count': 1}),
 (28, 27, {'count': 2}),
 (28, 5, {'count': 1}),
 (28, 22, {'count': 1}),
 (28, 29, {'count': 3}),
 (29, 6, {'count': 1}),
 (29, 27, {'count': 2}),
 (29, 28, {'count': 3}),
 (29, 5, {'count': 1}),
 (29, 22, {'count': 1})]

In this synthetic social network, the number of times the left student indicated that the right student was their favourite is stored in the "count" variable.

Exercise

Can you figure out the maximum times any student rated another student as their favourite?


In [10]:
# Answer
counts = [d['count'] for _, _, d in G.edges(data=True)]
maxcount = max(counts)

def test_maxcount(maxcount):
    assert maxcount == 3
    
test_maxcount(maxcount)

Exercise

We found out that there are two individuals that we left out of the network, individual no. 30 and 31. They are one male (30) and one female (31), and they are a pair that just love hanging out with one another and with individual 7 (count=3), in both directions per pair. Add this information to the graph.

If you need more help, check out https://networkx.readthedocs.io/en/stable/tutorial/index.html


In [11]:
# Answer
G.add_node(30, gender='male')
G.add_node(31, gender='female')
G.add_edge(30, 31, count=3)
G.add_edge(31, 30, count=3)
G.add_edge(30, 7, count=3)
G.add_edge(7, 30, count=3)
G.add_edge(31, 7, count=3)
G.add_edge(7, 31, count=3)

Verify that you have added in the edges and nodes correctly by running the following cell.


In [12]:
def test_graph_integrity(G):
    assert 30 in G.nodes()
    assert 31 in G.nodes()
    assert G.node[30]['gender'] == 'male'
    assert G.node[31]['gender'] == 'female'
    assert G.has_edge(30, 31)
    assert G.has_edge(30, 7)
    assert G.has_edge(31, 7)
    assert G.edge[30][7]['count'] == 3
    assert G.edge[7][30]['count'] == 3
    assert G.edge[31][7]['count'] == 3
    assert G.edge[7][31]['count'] == 3
    assert G.edge[30][31]['count'] == 3
    assert G.edge[31][30]['count'] == 3
    print('All tests passed.')
    
test_graph_integrity(G)


All tests passed.

Tests

A note about the tests: Testing is good practice when writing code. Well-crafted assertion statements help you program defensivel, by forcing you to explicitly state your assumptions about the code or data.

For more references on defensive programming, check out Software Carpentry's website: http://swcarpentry.github.io/python-novice-inflammation/08-defensive.html

For more information on writing tests for your data, check out these slides from a lightning talk I gave at Boston Python and SciPy 2015: http://j.mp/data-test

Coding Patterns

These are some recommended coding patterns when doing network analysis using NetworkX, which stem from my roughly two years of experience with the package.

Iterating using List Comprehensions

I would recommend that you use the following for compactness:

[d['attr'] for n, d in G.nodes(data=True)]

And if the node is unimportant, you can do:

[d['attr'] for _, d in G.nodes(data=True)]

Iterating over Edges using List Comprehensions

A similar pattern can be used for edges:

[n2 for n1, n2, d in G.edges(data=True)]

or

[n2 for _, n2, d in G.edges(data=True)]

If the graph you are constructing is a directed graph, with a "source" and "sink" available, then I would recommend the following pattern:

[(sc, sk) for sc, sk, d in G.edges(data=True)]

or

[d['attr'] for sc, sk, d in G.edges(data=True)]

Drawing Graphs

As illustrated above, we can draw graphs using the nx.draw() function. The most popular format for drawing graphs is the node-link diagram.


In [13]:
nx.draw(G)


If the network is small enough to visualize, and the node labels are small enough to fit in a circle, then you can use the with_labels=True argument.


In [14]:
nx.draw(G, with_labels=True)


However, note that if the number of nodes in the graph gets really large, node-link diagrams can begin to look like massive hairballs. This is undesirable for graph visualization.

Instead, we can use a matrix to represent them. The nodes are on the x- and y- axes, and a filled square represent an edge between the nodes. This is done by using the nx.to_numpy_matrix(G) function.

We then use matplotlib's pcolor(numpy_array) function to plot. Because pcolor cannot take in numpy matrices, we will cast the matrix as an array of arrays, and then get pcolor to plot it.


In [15]:
matrix = nx.to_numpy_matrix(G)

plt.pcolor(np.array(matrix))
plt.axes().set_aspect('equal') # set aspect ratio equal to get a square visualization
plt.xlim(min(G.nodes()), max(G.nodes())) # set x and y limits to the number of nodes present.
plt.ylim(min(G.nodes()), max(G.nodes()))
plt.title('Adjacency Matrix')
plt.show()


Let's try another visualization, the Circos plot. We can order the nodes in the Circos plot according to the node ID, but any other ordering is possible as well. Edges are drawn between two nodes.

Credit goes to Justin Zabilansky (MIT) for the implementation, and Jon Charest for improvements.


In [16]:
from circos import CircosPlot

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)

nodes = sorted(G.nodes())
edges = G.edges()
node_cmap = {'male':'blue', 'female':'red'}
nodecolors = [node_cmap[G.node[n]['gender']] for n in G.nodes()]

c = CircosPlot(nodes, edges, radius=10, ax=ax, fig=fig, nodecolor=nodecolors)
c.draw()  
plt.savefig('images/seventh.png', dpi=300)


This visualization helps us highlight nodes that there are poorly connected, and others that are strongly connected.

Next up, let's try Hive Plots.


In [17]:
from hiveplot import HivePlot

nodes = dict()
nodes['male'] = [n for n,d in G.nodes(data=True) if d['gender'] == 'male']
nodes['female'] = [n for n,d in G.nodes(data=True) if d['gender'] == 'female']

edges = dict()
edges['group1'] = G.edges(data=True)

nodes_cmap = dict()
nodes_cmap['male'] = 'blue'
nodes_cmap['female'] = 'red'

edges_cmap = dict()
edges_cmap['group1'] = 'black'

In [18]:
h = HivePlot(nodes, edges, nodes_cmap, edges_cmap)
h.draw()


Hive plots allow us to divide our nodes into sub-groups, and visualize the within- and between-group connectivity.


In [ ]: